using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace SpoonCore.Crypt
{
	public class Cert
	{
		private readonly SortedList<string, string> _data = new SortedList<string, string>();
		private byte[] _hash;

		public Cert(BinaryReader br)
		{
			int count = br.ReadInt32();
			while (count > 0)
			{
				string key = br.ReadString();
				string value = br.ReadString();
				_data.Add(key, value);
				count--;
			}

			count = br.ReadInt32();
			_hash = br.ReadBytes(count);
		}

		private byte[] Hash()
		{
			MemoryStream stream = new MemoryStream();
			BinaryWriter bw = new BinaryWriter(stream);

			StringBuilder str = new StringBuilder();
			foreach (KeyValuePair<string, string> item in _data)
			{
				bw.Write(item.Key);
				bw.Write(item.Value);
			}
			
			SHA256 hash = SHA256Managed.Create();
			return hash.ComputeHash(stream);

		}

		public byte[] GetBytes()
		{
			MemoryStream stream = new MemoryStream();
			BinaryWriter bw = new BinaryWriter(stream);

			bw.Write(_data.Count);
			foreach (KeyValuePair<string, string> item in _data)
			{
				bw.Write(item.Key);
				bw.Write(item.Value);
			}

			return stream.ToArray();
		}
	}
}
